<?php
/**
 * @file
 * Views functions.
 */

/**
 * Implementation of hook_views_plugins().
 */
function editview_location_views_plugins() {
  return array(
    'row' => array(
      'editview_location' => array(
        'title' => t('Editview location'),
        'help' => t('Displays a location edit form.'),
        'handler' => 'editview_plugin_row_location_edit',
        'path' => drupal_get_path('module', 'editview_location') .'/includes',
        'theme' => 'editview_view_row_location_edit',
        'theme path' => drupal_get_path('module', 'editview_location') .'/theme',
        'theme file' => 'editview_location.theme.inc',
        'base' => array('location'),
	'uses options' => TRUE,
        'uses fields' => FALSE,
        'type' => 'normal',
      ),
    ),
  );
}

/**
 * Menu callback; allow JavaScript to update node in view.
 */
function editview_location_js() {
  if (isset($_POST['form_build_id']) && isset($_POST['editview_location_view'])) {
    // Build the view so all necessary classes will be defined.
    $view = views_get_view($_POST['editview_location_view']);
    $view->build();
    // Retrive form from database.
    $form_build_id = $_POST['form_build_id'];
    $form_state = array('storage' => NULL, 'submitted' => FALSE);
    $form = form_get_cache($form_build_id, $form_state);
    // Submit location.
    $args = $form['#parameters'];
    $form_id = array_shift($args);
    $form_state['post'] = $form['#post'] = $_POST;
    drupal_process_form($form_id, $form, $form_state);
    // Load fresh copy of the node.
    unset($form_state['location']);
//TODO: understand: why it's needed to load location?
    $args[1] = location_load_location($form_state['values']['lid']);
    if (!empty($args[1])) {
      // Rebuild form until element IDs match originals.
      for ($i = 0; $i < $args[3]; $i++) {
        $form = drupal_rebuild_form($form_id, $form_state, $args, $form_build_id);
      }
      $response = drupal_render($form);
    }
    // Return form to user.
    drupal_json(theme('status_messages') . (isset($response) ? $response : ''));
  }
}

/**
 * Implementation of hook_forms().
 */
function editview_location_forms($form_id, $args) {
  $forms = array();
  if (!strncmp($form_id, 'editview_location_form_', 23)) {
    $forms[$form_id] = array(
      'callback' => 'editview_location_form',
    );
  }
  return $forms;
}

/**
 * Prepare a location form for the view.
 *
 * @param $form_state
 *   The form state array.
 * @param $node
 *   The node object.
 * @param $view
 *   The view object.
 * @return
 *   A node form array.
 * @ingroup forms
 * @see editview_node_form_submit()
 * @see editview_node_form_delete_submit()
 */
function editview_location_form(&$form_state, $location, $view, $order, $uri, $settings) {
  $element = array(
    '#type' => 'location_element',
    '#default_value' => $location,
    '#location_settings' => $settings,
  );
//TODO: investigate when to process form correctly
  $form = _location_expand_location($element);
  //drupal_alter('form', $element);
  unset($form['delete_location']);
  // Add the buttons.
  $form['buttons'] = array('#weight' => 99);
  $form['buttons']['submit'] = array(
    '#type' => 'submit',
    '#access' => !form_get_errors(),
    '#value' => t('Save'),
    '#weight' => 5,
    '#submit' => array('editview_location_form_submit'),
  );
  if (!empty($location->lid)) {
    $form['buttons']['delete'] = array(
      '#type' => 'submit',
      '#value' => t('Delete'),
      '#weight' => 15,
      '#submit' => array('editview_location_form_delete_submit'),
    );
  }

  $form['buttons']['link'] = array(
    '#type' => 'markup',
    '#weight' => 25,
    '#value' => "<a href='#$location[lid]'>[lid:$location[lid]]</a>",
  );

  $form['editview_location_view'] = array('#type' => 'hidden', '#value' => $view->name);
  $form['#id'] = form_clean_id($form['#id']);
  //$form['#theme'] = 'editview_location_form';
  $form['#theme'] = 'theme_location_element';
  $form['#cache'] = TRUE;
  $form['#action'] = $uri;
  
  return $form;
}

/**
 * Override the node submit redirect.
 *
 * If the form was submitted by JavaScript, do not redirect. Otherwise, redirect
 * to the requesting page.
 */
function editview_location_form_submit($form, &$form_state) {
  $uri = request_uri();
  location_save($form_state['values'], FALSE);
  
  if ($uri == $form['#parameters'][5] || !isset($form['#parameters'][2]->lid)) {
    global $base_root;
    $form_state['redirect'] = $base_root . $uri;
  }
  else {
    $form_state['redirect'] = FALSE;
  }
}

/**
 * Override the node delete redirect.
 */
function editview_location_form_delete_submit($form, &$form_state) {
  $lid = $form_state['values']['lid'];

  //Copied straight from location.module:835
  //TODO: refactor into dedicated method
  // An instance may have been deleted. Check reference count.
  $count = db_result(db_query('SELECT COUNT(*) FROM {location_instance} WHERE lid = %d', $lid));
  if ($count !== FALSE && $count == 0) {
    watchdog('location', 'Deleting unreferenced location with LID %lid.', array('%lid' => $lid));
    $location = array('lid' => $lid);
    location_invoke_locationapi($location, 'delete');
    db_query('DELETE FROM {location} WHERE lid = %d', $location['lid']);
  } else {
    drupal_set_message(t(
        'Cannot delete location [lid:%lid] because it is referenced %count times',
	array('%lid' => $lid, '%count' => $count)));
  }

  $uri = request_uri();
  global $base_root;
  $form_state['redirect'] =
    $uri == $form['#parameters'][5]
      ? $base_root . $uri
      : FALSE;
}